package com.sansecy.monitor.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ImageView;

/**
 * @Description DragImageView
 * @Date 2019-08-04 02:15
 * @Created by caoyu
 */
public class DragImageView extends android.support.v7.widget.AppCompatImageView {

    public DragImageView(Context context) {
        this(context, null);
    }

    public DragImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * 触摸时移动的位置
     */
    private int lastX;
    private int lastY;

    /**
     * 手指放下X和Y属性的位置
     */
    private int downX;
    private int downY;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.d(this.getClass().getName(), "onTouchEvent: ");
        //获取到手指处的横坐标和纵坐标
        int x = (int) event.getX();
        int y = (int) event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastX = x;
                lastY = y;
                downX = (int) getX();
                downY = (int) getY();
                break;
            case MotionEvent.ACTION_MOVE:
                //计算移动的距离
                int offX = x - lastX;
                int offY = y - lastY;
                setX(getX() + offX);
                setY(getY() + offY);
                break;
            case MotionEvent.ACTION_UP:
                if (downX == getX() && downY == getY()) {
                    performClick();
                }
                break;
        }
        return true;
    }

    @Override
    public boolean performClick() {
        Log.d(this.getClass().getName(), "performClick: ");

        return super.performClick();
    }
}
